<template>
  <div>
    <section-box title="已抽取试卷列表" class="random-box" style="margin-bottom: 25px">
      <el-col :span="20" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
            >导出抽卷报表
            </el-button>
          </el-col>
        </el-row>
      </el-col>
      <el-table
        ref="multipleTable"
        v-loading="loadingOut"
        row-key="paperId"
        :data="juanPaperOut"
        max-height="250"
      >
        <el-table-column label="卷库卷编码" align="center" prop="newPaperCode" show-overflow-tooltip/>
        <el-table-column label="抽卷时间" align="center" prop="takenOutTime" show-overflow-tooltip/>
        <el-table-column label="试卷名称" align="center" prop="paperName" show-overflow-tooltip/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-view" v-if="scope.row.paperType == '1'" @click="handleView(scope.row)">查看</el-button>
            <!-- <el-button
              v-hasPermi="['juan:juanPaper:remove']"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              >删除
            </el-button> -->
            <el-button
              v-hasPermi="['juan:juanPaper:analysis']"
              size="mini"
              type="text"
              icon="el-icon-data-analysis"
              @click="handleAnalysis(scope.row)"
            >数据分析
            </el-button>
            <el-button
              v-hasPermi="['juan:juanPaper:export']"
              v-if="scope.row.paperType == '1'"
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleExport(scope.row)"
            >导出EXCEL
            </el-button>
            <el-button
              v-hasPermi="['juan:juanPaper:export']"
              v-if="scope.row.paperType == '1'"
              size="mini"
              type="text"
              icon="el-icon-download"
              @click="handleExportJson(scope.row)"
            >导出数据包
            </el-button>
            <el-button
                v-hasPermi="['juan:juanPaper:export']"
                v-if="scope.row.paperType == '3'"
                size="mini"
                type="text"
                icon="el-icon-download"
                @click="handleDownloadPaper(scope.row)"
                >下载试卷
              </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="totalOut > 0"
        :total="totalOut"
        :page.sync="queryParamsOut.pageNum"
        :limit.sync="queryParamsOut.pageSize"
        @pagination="getOutList"
      />
    </section-box>

    <section-box title="卷库列表" class="random-box">
      <el-table v-loading="loading" :data="juanPaperList" max-height="250">
        <el-table-column label="卷库卷编码" align="center" prop="newPaperCode" show-overflow-tooltip/>
        <el-table-column label="试卷名称" align="center" prop="paperName" show-overflow-tooltip/>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </section-box>

    <div  style="margin-bottom: 25px">
      <span>随机数量：</span>
      <el-input-number size="mini" v-model="extractionNumber" :min="1" :precision="0" :step="1" step-strictly></el-input-number>
    </div>

    <div class="dialog-footer flex">
      <el-button type="primary" style="margin-right: 40px" :loading="buttonLoading" @click="submitRandom">抽卷</el-button>
      <el-button @click="close">关闭</el-button>
    </div>
  </div>
</template>

<script>
  import SectionBox from '../juanGenerate/components/SectionBox.vue'
  import {
    delJuanPaper,
    queryBeenTakenOutBakeupList,
    queryUnBeenTakenOutBakeupList,
    randomTakeOutPaper
  } from '@/api/juan/juanPaper'
  import request from '@/utils/request'

  export default {
    name: 'JuanPaper',
    components: { SectionBox },
    props: {
      courseId: {
        type: String,
        default: ''
      }
    },
    data() {
      return {
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        loadingOut: false,
        // 总条数
        total: 0,
        totalOut: 0,
        // 试卷表格数据
        juanPaperOut: [],
        juanPaperList: [],
        // 弹出层标题
        title: '',
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          courseId: undefined
        },
        queryParamsOut: {
          pageNum: 1,
          pageSize: 10,
          courseId: undefined
        },
        extractionNumber: 1
      }
    },
    mounted() {
      this.queryParams.courseId = this.courseId
      this.queryParamsOut.courseId = this.courseId
      this.handleQuery()
      this.handleQueryOut()
    },
    methods: {
      /** 待抽取试卷列表 */
      getList() {
        this.loading = true
        queryUnBeenTakenOutBakeupList(this.queryParams)
          .then((response) => {
            this.juanPaperList = response.rows
            this.total = response.total
            this.loading = false
          })
          .catch(() => {
            this.loading = false
          })
      },

      /** 已抽取试卷列表 */
      getOutList() {
        this.loadingOut = true
        queryBeenTakenOutBakeupList(this.queryParamsOut)
          .then((response) => {
            this.juanPaperOut = response.rows
            this.totalOut = response.total;
            this.loadingOut = false
          })
          .catch(() => {
            this.loadingOut = false
          })
      },
      // 取消按钮
      cancel() {
        this.open = false
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1
        this.getList()
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.handleQuery()
      },
      /** 搜索按钮操作 */
      handleQueryOut() {
        this.queryParamsOut.pageNum = 1
        this.getOutList()
      },
      /** 重置按钮操作 */
      resetQueryOut() {
        this.handleQueryOut()
      },
      /** 查看按钮操作 */
      handleView(row) {
        this.cancel()
        this.$router.push({
          path: '/juanPaper/juanPaper/edit',
          query: {
            paperId: row.paperId,
            page: 'view'
          }
        })
      },
      /** 数据分析按钮操作 */
      handleAnalysis(row) {
        this.cancel()
        this.$router.push({
          path: '/juanPaper/juanPaper/analysis',
          query: {
            paperId: row.paperId
          }
        })
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const paperIds = row.paperId || this.ids
        this.$modal
          .confirm('是否确认删除试卷？')
          .then(() => {
            this.loading = true
            return delJuanPaper(paperIds)
          })
          .then(() => {
            this.loading = false
            this.getList()
            this.$modal.msgSuccess('删除成功')
          })
          .catch(() => {
          })
          .finally(() => {
            this.loading = false
          })
      },
      /** 导出按钮操作 */
      handleExport(data) {
        this.download('juan/juanPaperBakeup/exportTakeOutPaperRecords' , {courseId: this.courseId}, `抽卷报表.xlsx`)
      },
      /** 导出数据包按钮操作 */
      handleExportJson(data) {
        // this.download('juan/juanPaper/exportPaperJson/' + data.paperId, {}, `juanPaper.json`)
        request({
          url: 'juan/juanPaper/exportPaperJson/' + data.paperId,
          method: 'post'
        }).then((res) => {
          this.saveJSON(res, res.juanPaper.paperName + `juanPaper.json`)
        })
      },
      saveJSON(data, filename) {
        if (!data) {
          return
        }
        if (!filename) {
          filename = 'json.json'
        }
        if (typeof data === 'object') {
          data = JSON.stringify(data, undefined, 4)
        }
        let blob = new Blob([data], { type: 'text/json' })
        let e = document.createEvent('MouseEvents')
        let a = document.createElement('a')
        a.download = filename
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        a.dispatchEvent(e)
      },
      // 下载试卷
      handleDownloadPaper(data) {
        this.download("juan/juanPaperBakeup/downloadPaper/" + data.id, {}, data.paperName + `.docx`);
      },
      //抽卷
      submitRandom() {
        if(this.extractionNumber > 0) {
          this.buttonLoading = true
          const params = {
            courseId: this.courseId,
            number: this.extractionNumber
          }
          randomTakeOutPaper(params)
            .then((response) => {
              this.buttonLoading = false
              this.$modal.msgSuccess('抽取成功')
              this.handleQuery()
              this.handleQueryOut()
              this.close();
            })
            .catch(() => {
              this.buttonLoading = false
            })
        } else {
          this.$modal.msgWarning("请设置数量");
        }
      },
      //关闭弹窗
      close() {
        this.$emit('close')
      }
    }
  }
</script>
<style>
  .random-box .section-header {
    background: transparent !important;
  }

  .random-box .section-body {
    padding: 20px !important;
    overflow-x: hidden;
  }
</style>
